package com.zunipe.trainticketsystem.database.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.zunipe.trainticketsystem.database.TrainTicketDBHelper;
import com.zunipe.trainticketsystem.database.entity.User;

import java.util.ArrayList;
import java.util.List;

public class UserDao {

    private final TrainTicketDBHelper dbHelper;

    public UserDao(Context context) {
        dbHelper = new TrainTicketDBHelper(context);
    }

    public List<User> findAll() {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        List<User> list = new ArrayList<>();
        try (Cursor cursor = database.rawQuery("SELECT * FROM users", new String[]{})) {
            while (cursor.moveToNext()) {
                Integer id = cursor.getInt(0);
                String username = cursor.getString(1);
                String phone = cursor.getString(2);
                User user = new User(id, username, phone);
                list.add(user);
            }
        }
        return list;
    }

    public User findById(int selectId) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        try (Cursor cursor = database.rawQuery("SELECT * FROM users WHERE id = ?", new String[]{String.valueOf(selectId)})) {
            if (cursor.moveToNext()) {
                Integer id = cursor.getInt(0);
                String username = cursor.getString(1);
                String phone = cursor.getString(2);
                return new User(id, username, phone);
            }
        }
        return null;
    }

    public void insert(User user) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        database.execSQL("INSERT INTO users(username, phone) VALUES(?, ?)", new Object[]{user.getUsername(), user.getPhone()});
    }

    public void update(User user) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        if (user.getUsername() != null)
            values.put("username", user.getUsername());
        if (user.getPhone() != null)
            values.put("phone", user.getPhone());
        database.update("users", values, "id = ?", new String[]{String.valueOf(user.getId())});
    }

    public void delete(User user) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        database.execSQL("DELETE FROM users WHERE id = ?", new Object[]{user.getId()});
    }
}
